<template>
  <teleport to="body">
    <div 
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 transition-opacity duration-300"
      :class="{ 'opacity-0 pointer-events-none': !visible }"
      @click="handleClose"
    >
      <div 
        class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all duration-300"
        :class="{ 'scale-95 opacity-0': !visible, 'scale-100 opacity-100': visible }"
        @click.stop
      >
        <!-- 模态框头部 -->
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-medium text-gray-900">{{ title }}</h3>
          <button 
            class="text-gray-400 hover:text-gray-500 focus:outline-none"
            @click="handleClose"
            aria-label="关闭"
          >
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <!-- 模态框内容 -->
        <div class="px-6 py-5">
          <form @submit.prevent="handleSubmit">
            <div class="space-y-4">
              <div>
                <label for="group-name" class="block text-sm font-medium text-gray-700 mb-1">
                  权限组名称 <span class="text-red-500">*</span>
                </label>
                <input
                  id="group-name"
                  v-model="form.name"
                  type="text"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                  placeholder="输入权限组名称"
                  :class="errors.name ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''"
                  @blur="validateField('name')"
                  :disabled="form.isSystemGroup"
                >
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>
              
              <div>
                <label for="group-description" class="block text-sm font-medium text-gray-700 mb-1">
                  描述
                </label>
                <textarea
                  id="group-description"
                  v-model="form.description"
                  rows="3"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-colors"
                  placeholder="描述该权限组的用途和包含的权限范围"
                  :disabled="form.isSystemGroup"
                ></textarea>
              </div>
              
              <div v-if="form.isSystemGroup" class="bg-yellow-50 p-3 rounded-md flex items-start">
                <i class="fa fa-info-circle text-yellow-500 mt-0.5 mr-2"></i>
                <p class="text-sm text-yellow-700">
                  这是系统内置权限组，不能修改名称
                </p>
              </div>
            </div>
          </form>
        </div>
        
        <!-- 模态框底部 -->
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button
            type="button"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors"
            @click="handleClose"
          >
            取消
          </button>
          <button
            type="button"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors"
            @click="handleSubmit"
            :disabled="submitting || form.isSystemGroup"
          >
            <i class="fa fa-save mr-1"></i>
            <span v-if="!submitting">保存</span>
            <span v-if="submitting" class="flex items-center">
              <i class="fa fa-spinner fa-spin mr-1"></i> 保存中...
            </span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script>
import { ref, watch } from 'vue';

export default {
  name: 'PermissionGroupModal',
  props: {
    // 控制模态框显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 权限组数据，编辑时传入
    group: {
      type: Object,
      default: () => ({})
    },
    // 模态框标题
    title: {
      type: String,
      default: '权限组设置'
    }
  },
  emits: ['close', 'save'],
  setup(props, { emit }) {
    // 表单数据
    const form = ref({
      id: '',
      name: '',
      description: '',
      isSystemGroup: false
    });
    
    // 错误信息
    const errors = ref({
      name: ''
    });
    
    // 提交状态
    const submitting = ref(false);
    
    // 监听权限组数据变化，初始化表单
    watch(() => props.group, (newVal) => {
      if (newVal && Object.keys(newVal).length > 0) {
        form.value = { ...newVal };
      } else {
        form.value = {
          id: '',
          name: '',
          description: '',
          isSystemGroup: false
        };
      }
      // 重置错误信息
      errors.value.name = '';
    }, { immediate: true });
    
    // 验证字段
    const validateField = (field) => {
      const value = form.value[field];
      errors.value[field] = '';
      
      if (field === 'name') {
        if (!value || value.trim() === '') {
          errors.value[field] = '请输入权限组名称';
        } else if (value.length > 50) {
          errors.value[field] = '权限组名称不能超过50个字符';
        }
      }
    };
    
    // 完整表单验证
    const validateForm = () => {
      let isValid = true;
      
      validateField('name');
      if (errors.value.name) {
        isValid = false;
      }
      
      return isValid;
    };
    
    // 处理提交
    const handleSubmit = async () => {
      if (submitting.value || form.value.isSystemGroup) return;
      
      if (!validateForm()) {
        // 聚焦到错误字段
        document.getElementById('group-name').focus();
        return;
      }
      
      try {
        submitting.value = true;
        // 触发保存事件，将表单数据传递给父组件
        emit('save', { ...form.value });
      } catch (error) {
        console.error('提交权限组数据失败:', error);
      } finally {
        submitting.value = false;
      }
    };
    
    // 处理关闭
    const handleClose = () => {
      if (!submitting.value) {
        emit('close');
      }
    };
    
    return {
      form,
      errors,
      submitting,
      validateField,
      handleSubmit,
      handleClose
    };
  }
};
</script>
